using System.Windows;
using System.Windows.Controls;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using DocumentCreationSystem.Services;
using DocumentCreationSystem.Models;

namespace DocumentCreationSystem.Views
{
    /// <summary>
    /// SettingsDialog.xaml 的交互逻辑
    /// </summary>
    public partial class SettingsDialog : Window
    {
        private readonly IConfiguration _configuration;
        private readonly ILogger<SettingsDialog> _logger;
        private readonly IVectorService _vectorService;
        private readonly IAIService _aiService;

        public SettingsDialog(IServiceProvider serviceProvider)
        {
            InitializeComponent();
            
            _configuration = serviceProvider.GetRequiredService<IConfiguration>();
            _logger = serviceProvider.GetRequiredService<ILogger<SettingsDialog>>();
            _vectorService = serviceProvider.GetRequiredService<IVectorService>();
            _aiService = serviceProvider.GetRequiredService<IAIService>();

            InitializeSettings();
            SettingsNavigation.SelectionChanged += SettingsNavigation_SelectionChanged;
        }

        private void InitializeSettings()
        {
            // 加载AI设置
            ZhipuApiKeyTextBox.Text = _configuration["AI:ZhipuAI:ApiKey"] ?? "";
            ZhipuBaseUrlTextBox.Text = _configuration["AI:ZhipuAI:BaseUrl"] ?? "https://open.bigmodel.cn/api/paas/v4";
            OllamaBaseUrlTextBox.Text = _configuration["AI:Ollama:BaseUrl"] ?? "http://localhost:11434";
            LMStudioBaseUrlTextBox.Text = _configuration["AI:LMStudio:BaseUrl"] ?? "http://localhost:1234";

            // 设置默认提供者
            var defaultProvider = _configuration["AI:DefaultProvider"] ?? "ZhipuAI";
            foreach (ComboBoxItem item in DefaultProviderComboBox.Items)
            {
                if (item.Tag?.ToString() == defaultProvider)
                {
                    DefaultProviderComboBox.SelectedItem = item;
                    break;
                }
            }

            // 设置默认模型
            var defaultModel = _configuration["AI:DefaultModel"] ?? "glm-4";
            foreach (ComboBoxItem item in ZhipuModelComboBox.Items)
            {
                if (item.Tag?.ToString() == defaultModel)
                {
                    ZhipuModelComboBox.SelectedItem = item;
                    break;
                }
            }

            // 设置AI参数
            TemperatureSlider.Value = _configuration.GetValue<float>("AI:DefaultTemperature", 0.7f);
            MaxTokensTextBox.Text = _configuration.GetValue<int>("AI:DefaultMaxTokens", 2000).ToString();
            EnableThinkingChainCheckBox.IsChecked = _configuration.GetValue<bool>("AI:EnableThinkingChain", true);

            // 加载向量数据库设置
            QdrantUrlTextBox.Text = _configuration["Vector:Qdrant:Url"] ?? "http://localhost:6333";
            CollectionNameTextBox.Text = _configuration["Vector:Qdrant:CollectionName"] ?? "documents";
            VectorSizeTextBox.Text = _configuration["Vector:Qdrant:VectorSize"] ?? "1024";

            // 加载文档设置
            AutoSaveCheckBox.IsChecked = bool.Parse(_configuration["Application:AutoBackup"] ?? "true");
            AutoSaveIntervalTextBox.Text = (_configuration.GetValue<int>("Novel:AutoSaveInterval") / 1000).ToString();
            AutoBackupCheckBox.IsChecked = bool.Parse(_configuration["Application:AutoBackup"] ?? "true");

            // 加载主题设置
            var theme = _configuration["Application:Theme"] ?? "Light";
            foreach (ComboBoxItem item in ThemeComboBox.Items)
            {
                if (item.Tag?.ToString() == theme)
                {
                    ThemeComboBox.SelectedItem = item;
                    break;
                }
            }
        }

        private void SettingsNavigation_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (SettingsNavigation.SelectedIndex < 0) return;

            // 隐藏所有面板
            AISettingsPanel.Visibility = Visibility.Collapsed;
            VectorSettingsPanel.Visibility = Visibility.Collapsed;
            DocumentSettingsPanel.Visibility = Visibility.Collapsed;
            ThemeSettingsPanel.Visibility = Visibility.Collapsed;

            // 显示选中的面板
            switch (SettingsNavigation.SelectedIndex)
            {
                case 0:
                    AISettingsPanel.Visibility = Visibility.Visible;
                    break;
                case 1:
                    VectorSettingsPanel.Visibility = Visibility.Visible;
                    break;
                case 2:
                    DocumentSettingsPanel.Visibility = Visibility.Visible;
                    break;
                case 3:
                    ThemeSettingsPanel.Visibility = Visibility.Visible;
                    break;
            }
        }

        private async void TestVectorConnection_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var button = sender as Button;
                if (button != null)
                {
                    button.IsEnabled = false;
                    button.Content = "测试中...";
                }

                var isConnected = await _vectorService.CheckConnectionAsync();
                
                MessageBox.Show(
                    isConnected ? "向量数据库连接成功！" : "向量数据库连接失败，请检查配置。",
                    "连接测试",
                    MessageBoxButton.OK,
                    isConnected ? MessageBoxImage.Information : MessageBoxImage.Warning);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "测试向量数据库连接时发生错误");
                MessageBox.Show($"连接测试失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                var button = sender as Button;
                if (button != null)
                {
                    button.IsEnabled = true;
                    button.Content = "测试连接";
                }
            }
        }

        private void Save_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 这里应该保存设置到配置文件
                // 由于appsettings.json通常是只读的，实际应用中可能需要使用用户配置文件
                
                MessageBox.Show("设置已保存！\n注意：某些设置需要重启应用程序才能生效。", 
                              "保存成功", MessageBoxButton.OK, MessageBoxImage.Information);
                
                DialogResult = true;
                Close();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存设置时发生错误");
                MessageBox.Show($"保存设置失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void Reset_Click(object sender, RoutedEventArgs e)
        {
            var result = MessageBox.Show("确定要重置所有设置为默认值吗？", "确认重置", 
                                       MessageBoxButton.YesNo, MessageBoxImage.Question);
            
            if (result == MessageBoxResult.Yes)
            {
                // 重置为默认值
                ZhipuApiKeyTextBox.Text = "";
                ZhipuBaseUrlTextBox.Text = "https://open.bigmodel.cn/api/paas/v4";
                OllamaBaseUrlTextBox.Text = "http://localhost:11434";
                LMStudioBaseUrlTextBox.Text = "http://localhost:1234";
                
                QdrantUrlTextBox.Text = "http://localhost:6333";
                CollectionNameTextBox.Text = "documents";
                VectorSizeTextBox.Text = "1024";
                
                AutoSaveCheckBox.IsChecked = true;
                AutoSaveIntervalTextBox.Text = "30";
                AutoBackupCheckBox.IsChecked = true;
                
                ThemeComboBox.SelectedIndex = 0; // Light theme
                PrimaryColorComboBox.SelectedIndex = 0; // DeepPurple
            }
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }

        private void DefaultProvider_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // 当默认提供者改变时，可以执行相关逻辑
            if (DefaultProviderComboBox.SelectedItem is ComboBoxItem item)
            {
                var provider = item.Tag?.ToString();
                _logger.LogInformation($"默认AI提供者已更改为: {provider}");
            }
        }

        private async void TestZhipuConnection_Click(object sender, RoutedEventArgs e)
        {
            await TestAIConnection("ZhipuAI", sender as Button);
        }

        private async void TestOllamaConnection_Click(object sender, RoutedEventArgs e)
        {
            await TestAIConnection("Ollama", sender as Button);
        }

        private async void TestLMStudioConnection_Click(object sender, RoutedEventArgs e)
        {
            await TestAIConnection("LMStudio", sender as Button);
        }

        private async Task TestAIConnection(string provider, Button? button)
        {
            try
            {
                if (button != null)
                {
                    button.IsEnabled = false;
                    button.Content = "测试中...";
                }

                // 这里应该调用相应的AI服务进行连接测试
                var isConnected = await TestAIServiceConnection(provider);

                MessageBox.Show(
                    isConnected ? $"{provider} 连接成功！" : $"{provider} 连接失败，请检查配置。",
                    "连接测试",
                    MessageBoxButton.OK,
                    isConnected ? MessageBoxImage.Information : MessageBoxImage.Warning);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"测试{provider}连接时发生错误");
                MessageBox.Show($"连接测试失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                if (button != null)
                {
                    button.IsEnabled = true;
                    button.Content = "测试连接";
                }
            }
        }

        private async Task<bool> TestAIServiceConnection(string provider)
        {
            try
            {
                // 获取可用模型列表来测试连接
                var models = await _aiService.GetAvailableModelsAsync();
                return models.Any(m => m.Provider == provider && m.IsAvailable);
            }
            catch
            {
                return false;
            }
        }

        private async void RefreshOllamaModels_Click(object sender, RoutedEventArgs e)
        {
            await RefreshModels("Ollama", OllamaModelsListBox, sender as Button);
        }

        private async void RefreshLMStudioModels_Click(object sender, RoutedEventArgs e)
        {
            await RefreshModels("LMStudio", LMStudioModelsListBox, sender as Button);
        }

        private async Task RefreshModels(string provider, ListBox listBox, Button? button)
        {
            try
            {
                if (button != null)
                {
                    button.IsEnabled = false;
                    button.Content = "刷新中...";
                }

                listBox.Items.Clear();

                var models = await _aiService.GetAvailableModelsAsync();
                var providerModels = models.Where(m => m.Provider == provider).ToList();

                foreach (var model in providerModels)
                {
                    var item = new ListBoxItem
                    {
                        Content = $"{model.Name} ({model.Description})",
                        Tag = model.Id
                    };
                    listBox.Items.Add(item);
                }

                if (!providerModels.Any())
                {
                    listBox.Items.Add(new ListBoxItem
                    {
                        Content = "未找到可用模型",
                        IsEnabled = false
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"刷新{provider}模型列表时发生错误");
                listBox.Items.Clear();
                listBox.Items.Add(new ListBoxItem
                {
                    Content = $"加载失败: {ex.Message}",
                    IsEnabled = false
                });
            }
            finally
            {
                if (button != null)
                {
                    button.IsEnabled = true;
                    button.Content = "刷新模型列表";
                }
            }
        }
    }
}
